import { User } from '../entities/entities';
import { Injectable } from '@angular/core';
import { LocalStorageService } from 'angular-2-local-storage';
import { JwtHelper, tokenNotExpired } from 'angular2-jwt';
import { TOKEN_STORAGE_KEY, USER_STORAGE_KEY } from '../app.config';
import { Admin } from 'shared/model/defination';

export interface SessionUser {
    Id: number;
    UserName: string;
    Roles: Array<string>;
}

export const enum ROLES {
    SUPER = '管理员',
    PROPERTY = '项目管理员',
    HR = '公司行政／HR',
    RECP = '前台'
}

@Injectable()
export class SessionService {
    private _jwtHelper: JwtHelper = new JwtHelper();

    public static errCount: number = 0;

    private _user: Admin;

    private _token: string;

    constructor(private _storage: LocalStorageService) { }

    isAuthorized: boolean;

    create(token: string, user: Admin): void {
        this._token = token;
        this.isAuthorized = true;
        this.setAuthTag(true);
        this._storage.set(TOKEN_STORAGE_KEY, token);
        this._storage.set(USER_STORAGE_KEY, user);
        this._user = user;
    }

    public isAuth(): boolean {
        const token = this.getToken();
        if (!token) {
            return false;
        }
        return !this._jwtHelper.isTokenExpired(token);
    }

    setAuthTag(tag: boolean) {
        this._storage.set('IS_AUTH', tag);
    }

    private _parseUserFromJwt(token: string): SessionUser {
        if (!token) {
            throw { status: 401, msg: '登录凭据不存在!' };
        }
        const decoded = this._jwtHelper.decodeToken(token as string);
        console.log(decoded);
        const user: SessionUser = {
            Id:
                decoded[
                'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/sid'
                ],
            UserName: decoded.sub,
            Roles: [
                decoded[
                'http://schemas.microsoft.com/ws/2008/06/identity/claims/role'
                ]
            ]
        };

        return user;
    }

    // async getCurrentUser(): Promise<SessionUser> {
    getCurrentUser(): Admin {
        if (typeof this._user !== 'undefined') {
            return this._user;
            // return Promise.resolve(this._user);
        } else {
            return this._storage.get(USER_STORAGE_KEY);
            // return Promise.resolve(user);
        }
    }

    // async getRoles(): Promise<any> {
    getRoles(): any {
        const user = this.getCurrentUser();
        return user ? user.roles : [];
    }

    get isUserAdmin() {
        const roles = this.getRoles();
        if (roles.length === 0) {
            return false;
        }
        return roles[0].roleName === ROLES.SUPER;
    }

    get isUserProperty() {
        const roles = this.getRoles();
        if (roles.length === 0) {
            return false;
        }
        return roles[0].roleName === ROLES.PROPERTY || roles[0].roleName === ROLES.RECP;
    }

    get isUserHr() {
        const roles = this.getRoles();
        if (roles.length === 0) {
            return false;
        }
        return roles[0].roleName === ROLES.HR;
    }

    get Managable() {
        const manager = this.getCurrentUser();

        return manager && manager.managements && manager.managements.length
            ? manager.managements[0].managable
            : {};
        // let manageType = manager.managements[0].manage_type;
        // if (manageType === "App\\Services\\Project\\Project") {

        // }
    }

    getToken(): string {
        return this._storage.get(TOKEN_STORAGE_KEY) as string;
    }

    destroy(): void {
        this._token = null;
        this._user = null;
        this._storage.clearAll();
    }
}
